package com.mongo.jdbc.core;

import java.net.URI;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author:binggong
 * @createtime: 2023年12月9日 下午11:42:42
 * @version:V.0.1
 * @tag: mongodb url 解析
 *
 */

public class ConnectionUrlParse {

	private static final Pattern HOST_LIST_PTRN = Pattern.compile("^\\[(?<hosts>.*)\\]$");

	private static final Pattern SCHEME_PTRN = Pattern.compile("(?<scheme>[\\w:%]+).*");

	/**
	 * 解析url信息，解析的URL放到properties对象中
	 * 
	 * @param url        mongodb jdbc url
	 * @param properties
	 * @return 返回
	 */
	public static Properties getParseMongoUrl(String url, Properties properties) {

		if (url != null && url.toLowerCase().trim().startsWith("jdbc:mongo://")) {
			// 解析配置参数

			int tempIndex = url.indexOf("?");
			String tmpParseUrl = url.substring(tempIndex + 1);
			url = url.substring(0, tempIndex);
			String paramters[] = tmpParseUrl.split("&");
			for (String par : paramters) {
				String pararr[] = par.split("=");
				properties.put(pararr[0].trim(), pararr[1].trim());
			}

			tempIndex = url.lastIndexOf("/");
			String dbname = url.substring(tempIndex + 1);
			url = url.substring(0, tempIndex);
			tempIndex = url.lastIndexOf("/");
			String address = url.substring(tempIndex + 1);

			properties.put("address", address);
			properties.put("dbname", dbname);

		}

		return properties;
	}

}
